import pytest
import requests
from utils.logger_util import logger
from utils.request_util import host, Request

# 插件配置已移动到项目根目录的 conftest.py 中
log=logger.getlog()

@pytest.fixture(scope='function')
def initial_activity_count(db_util):
    sql = """SELECT COUNT(*) count
             FROM activity"""
    n = db_util.execute(sql)
    yield n[0]['count']



@pytest.fixture(scope='function')
def create_activity_schema():
    yield {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "code": {
                "type": "integer"
            },
            "data": {
                "type": ["object", 'null'],
                "properties": {
                    "activityId": {
                        "type": "integer"
                    }
                },
                "additionalProperties": False,
                "required": [
                    "activityId"
                ]
            },
            "msg": {
                "type": "string"
            }
        },
        "additionalProperties": False,
        "required": [
            "code",
            "data",
            "msg"
        ]
    }


@pytest.fixture(scope='session')
def get_activity_list_schema():
    yield {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "code": {
            "type": "integer"
        },
        "data": {
            "type": "object",
            "properties": {
                "total": {
                    "type": "integer"
                },
                "records": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "activityId": {
                                "type": "integer"
                            },
                            "activityName": {
                                "type": "string"
                            },
                            "description": {
                                "type": "string"
                            },
                            "valid": {
                                "type": "boolean"
                            },
                            "duration": {
                                "type": "integer"
                            },
                            "createTime": {
                                "type": "string"
                            }
                        },
                        "additionalProperties": False,
                        "required": [
                            "activityId",
                            "activityName",
                            "description",
                            "valid",
                            "duration",
                            "createTime"
                        ]
                    }
                }
            },
            "additionalProperties": False,
            "required": [
                "total",
                "records"
            ]
        },
        "msg": {
            "type": "string"
        }
    },
    "additionalProperties": False,
    "required": [
        "code",
        "data",
        "msg"
    ]
}


@pytest.fixture(scope='function')
def get_activity_detail_schema():
    yield {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "code": {
            "type": "integer"
        },
        "data": {
            "type": "object",
            "properties": {
                "activityId": {
                    "type": "integer"
                },
                "activityName": {
                    "type": "string"
                },
                "description": {
                    "type": "string"
                },
                "valid": {
                    "type": "boolean"
                },
                "prizes": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "prizeId": {
                                "type": "integer"
                            },
                            "name": {
                                "type": "string"
                            },
                            "imageUrl": {
                                "type": "string"
                            },
                            "price": {
                                "type": "number"
                            },
                            "description": {
                                "type": "string"
                            },
                            "prizeTierName": {
                                "type": "string"
                            },
                            "prizeAmount": {
                                "type": "integer"
                            },
                            "valid": {
                                "type": "boolean"
                            }
                        },
                        "additionalProperties": False,
                        "required": [
                            "prizeId",
                            "name",
                            "imageUrl",
                            "price",
                            "description",
                            "prizeTierName",
                            "prizeAmount",
                            "valid"
                        ]
                    }
                },
                "users": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "userId": {
                                "type": "integer"
                            },
                            "userName": {
                                "type": "string"
                            },
                            "valid": {
                                "type": "boolean"
                            }
                        },
                        "additionalProperties": False,
                        "required": [
                            "userId",
                            "userName",
                            "valid"
                        ]
                    }
                }
            },
            "additionalProperties": False,
            "required": [
                "activityId",
                "activityName",
                "description",
                "valid",
                "prizes",
                "users"
            ]
        },
        "msg": {
            "type": "string"
        }
    },
    "additionalProperties": False,
    "required": [
        "code",
        "data",
        "msg"
    ]
}





def _build_body(activity_data,prizes,users):
    prize_list=[]
    user_list=[]
    prize_tiers = ["FIRST_PRIZE", "SECOND_PRIZE", "THIRD_PRIZE"]
    for i,prize_conf in enumerate(activity_data.get('prizes',[1])):
        if i<len(prizes):
            prize_list.append({
                'prizeId': prizes[i]['prize_id'],
                'prizeAmount': prize_conf.get('amount', 1),
                'prizeTiers': prize_tiers[i%3]
            })

    for i , user_index in enumerate(activity_data.get('user_indices',[1,2,3])):
        if user_index<len(users):
            user_list.append({
                'userId': users[user_index]['user_id'],
                'userName': users[user_index]['user_info']['name']
            })
    return {
        'activityName': activity_data['name'],
        'description': activity_data['description'],
        'duration': activity_data['duration'],
        'activityPrizeList': prize_list,
        'activityUserList': user_list
    }


def _send_create_request(url,token, body):
    """发送创建活动请求"""
    headers = {
        'Content-Type': 'application/json',
        'user_token': token
    }

    log.info(f"发送创建活动请求: {url}")
    log.info(f"请求体: {body}")

    response = requests.post(url, json=body, headers=headers)

    log.info(f"响应状态码: {response.status_code}")
    log.info(f"响应内容: {response.text}")

    return response

# 新增一个别名夹具，在本目录复用 create_six_price
@pytest.fixture(scope='function')
def create_activity_list(create_three_prizes, register_seven_users,get_token):
    """四个活动"""
    activity_data = [
        {
            "name": "双11购物节",
            "description": "双十一全场折扣优惠活动",
            "duration": 24,
            "prizes": [
                {"amount": 1},
                {"amount": 1},
                {"amount": 1}
            ],
            "user_indices": [1, 2, 3],
            "test_name": "标准三奖品三用户活动"
        },
        {
            "name": "春节大促销",
            "description": "新春佳节特惠活动，好礼送不停",
            "duration": 72,
            "prizes": [
                {"amount": 1},
                {"amount": 1},
                {"amount": 1}
            ],
            "user_indices": [0, 1, 2, 3, 4, 5, 6],
            "test_name": "少奖品，多用户"
        },
        {
            "name": "VIP会员日",
            "description": "VIP会员专属优惠日，尊享特权",
            "duration": 0,
            "prizes": [
                {"amount": 1},
                {"amount": 1},
                {"amount": 1}
            ],
            "user_indices": [0, 2, 4, 6],
            "test_name": "永久活动测试"
        },
        {
            "name": "周末特惠",
            "description": "周末限时特价活动",
            "duration": 48,
            "prizes": [
                {"amount": 1},
                {"amount": 2}
            ],
            "user_indices": [1, 2, 3, 4],
            "test_name": "奖品数量少于用户数量"
        }
    ]
    create_activity_url=host+'activity/create'
    activity_list = []

    for prize_info in activity_data:
        body= _build_body(prize_info,create_three_prizes,register_seven_users)
        r=_send_create_request(create_activity_url,get_token, body)
        assert r.json()['data'] is not None,'创建活动后，返回的data不能为空'
        assert isinstance(r.json()['data']['activityId'], int), '没有返回有效的活动id'
        assert r.json()['code'] == 200 or r.json()['code'] == 0,'创建活动失败'
        body['activityId'] = r.json()['data']['activityId']
        activity_list.append(body)

    activity_list.reverse()
    yield activity_list





